
import {
  formatDateArray,
  getDate,
  getWeekDate,
  formatDate
} from "../../../js/util.js";
import loading from '/js/loading.js'
let state = JSON.parse(localStorage.getItem('information'))?.state || 1
let loginRTM
import * as teacherLogin from '/views/menu/student/components/message/rtmToken.js'
import * as studentLogin from '/views/menu/teacher/components/message/rtmToken.js'
if (state === 0) {
  loginRTM = studentLogin.default
} else {
  loginRTM = teacherLogin.default
}
let currentPage = 1,
  index = 1,
  n = {},
  total = 0,
  allPage = 0,
  getParams = {
    pageNum: currentPage,
    pageSize: 10,
    dialect: '',//语言
    language: '', //其他会讲
    teachingt: '', //授课时间
    lecturet: '',//时间段
    birthplace: '', //出生地
    price: '',//价格
    name: '',//老师名称
    timequantum: '',//精确时间点(开始点)
    timequantum1: '',//精确时间点(结束点)
    coursetime: '',//星期几
    price1: 1,//最终价格
    star: 1,//星级 状态：5精确查询 1:降序查询
    state: 3
  },
  currentlist = {},
  clickDay = 0,
  currentId = 0,//当前所选的老师id
  clickTime = '',
  dateOfToday = Date.now(),
  dayOfToday = (new Date().getDay() + 7 - 1) % 7,
  // according this week
  daysOfThisWeek = Array.from(new Array(7)).map((_, i) => {
    const date = new Date(dateOfToday + (i - dayOfToday) * 1000 * 60 * 60 * 24)
    return date.getFullYear() +
      '-' +
      String(date.getMonth() + 1).padStart(2, '0') +
      '-' +
      String(date.getDate()).padStart(2, '0')
  }),
  time = Intl.DateTimeFormat().resolvedOptions().timeZone,
  now = new Date(),
  date = formatDateArray(daysOfThisWeek[0]),
  newDate = formatDateArray(daysOfThisWeek[6]),
  hour = now.getHours() > 10 ? now.getHours() : now.getHours() + "0",
  minute = now.getMinutes() > 10 ? now.getMinutes() : "0" + now.getMinutes(),
  teacherTime = [],
  list = [],
  list2 = [],
  bestTeacher = [],
  clients = null //agora client 


let activeTime = {
  0: "00:00",
  1: "01:00",
  2: "02:00",
  3: "03:00",
  4: "04:00",
  5: "05:00",
  6: "06:00",
  7: "07:00",
  8: "08:00",
  9: "09:00",
  10: "10:00",
  11: "11:00",
  12: "12:00",
  13: "13:00",
  14: "14:00",
  15: "15:00",
  16: "16:00",
  17: "17:00",
  18: "18:00",
  19: "19:00",
  20: "20:00",
  21: "21:00",
  22: "22:00",
  23: "23:00",
  24: "24:00",
};

let getTeacher = async () => {
  initTeacherTime()
  if (window.location.href.split('?')[1]?.split('=')[0] === 'name') {
    getParams.name = window.location.href.split('?')[1].split('=')[1]
    $('.header-input')[0].value = getParams.name
  }
  let res = await ajax("query_teacher_puls", getParams, "post");
  let res2 = await ajax("query_teacher_puls", {
    state: 1,
    price1: "1"
  }, "post");
  list = res.data.list.splice(0, 4)
  list2 = res.data.list
  window.list = list
  window.list2 = list2
  total = res.data.total
  bestTeacher = res2.data.list.splice(0, 3)
  onload()
}

let onload = function () {
  listenerAgora()
  createTeacherList()
  createBestTeacherList()
  createTeacherList2()
  createPage()
  createOtherBottom()
  lastPageListener()
  nextPageListener()
  clickPageListener()
  listenerDialogOpen()
  listenerTop()
  priceChangeListener()
}

let clearBlock20Style = () => {
  $('.block20')[0].style.marginTop = '40px'
}

let listenerDialogOpen = () => {
  $('.block39').each(function (index) {
    $(this).on('click', function () {
      if (!localStorage.getItem('Token')) { window.location.href = '/index.html' }
      if (JSON.parse(localStorage.getItem('information')).state === 1) {
        Dreamer.error('老师不可以购买课程', 2000)
        return
      }
      document.body.scrollIntoView()
      let { index, teacherid } = $(this).parents('.block19')[0].dataset
      index = index - 1
      dialogOneStep(list[index])
      sureButton()
    })
  })

  $(".block40").each(function (index) {
    $(this).on("click", function () {
      if (!localStorage.getItem('Token')) { window.location.href = '/index.html' }
      else {
        document.body.scrollIntoView()
        let { index, teacherid } = $(this).parents('.block19')[0].dataset
        index = index - 1
        teacherid = parseInt(teacherid)
        $(".dialog4")[0] && $(".dialog4")[0].remove();
        dialogMessage(list[index]);
        $('.source')[0].src = list[index].teacherimg
        $('.right-send')[0].addEventListener('click', async () => {
          let studentid = parseInt(JSON.parse(localStorage.getItem('user')).user_id)
          let reason = $('.right-select')[0].value
          let target = $('.right-attend')[0].innerText
          let curriculum = $('.right-bottom-content')[0].innerHTML
          if (!reason) {
            Dreamer.warning("请输选择原因！", 2000);
            return
          }
          if (!target) {
            Dreamer.warning("请输入目标", 2000);
            return
          }
          if (!curriculum) {
            Dreamer.warning("请输入消息！", 2000);
            return
          }
          let params = {
            reason,
            target,
            parent_id: '',
            frequency: 5,
            createtime: formatDate(new Date()),
            curriculum,
            content: curriculum,
            studentid,
            teacherid,
            state: 2,
          }
          let options = {
            enableHistoricalMessaging: true,
            enableOfflineMessaging: true
          }
          let res = await clients.sendMessageToPeer(
            { text: `<div>${curriculum}</div>` },
            params.teacherid + '',
            options
          )
          let res2 = await ajax('information_addition_add', params, 'post')
          if (res && res2.code === 200) {
            console.log(res)
            Dreamer.success("send success", 2000);
            $(".dialog1")[0] && $(".dialog1")[0].remove();
            $(".dialog2")[0] && $(".dialog2")[0].remove();
            $(".dialog3")[0] && $(".dialog3")[0].remove();
            $(".dialog4")[0] && $(".dialog4")[0].remove();
            $("#mask")[0].style.display = "none";
            return
          } else {
            console.log(res2)
            Dreamer.error("send error", 2000);
          }

          // websocketListener(params)
        })
      }
    });
  });


}

let initTeacherTime = () => {
  teacherTime = []
  for (let i = 0; i < 7; i++) {
    let item = {
      weekday: getWeekDate(new Date(daysOfThisWeek[i]).getTime()),
      day: new Date(daysOfThisWeek[i]).getDate(),
      weekdaynum: i + 1,
      time: [
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
      ],
    };
    teacherTime.push(item);
  }
}



let dialogPublicTop = (number) => {
  let div = document.createElement("div");
  div.className = "dialog1-top";
  let image = `
        <img width='36' height='35' src='/static/anquan.png'/>
    `;
  let title = `
        <div>
            <span>${number}</span>
            <span style='color:#9C9C9C;margin-left:-6px'>/4</span>
            <span style='color:#9C9C9C'>步</span>
        </div>
    `;
  let close = `
        <i class='iconfont icon-chahao close'></i>
    `;
  //<i class='iconfont icon-xiangyou1 leftallow' style='margin-left: 13px;margin-right: 13px;transform: rotateY(185deg);'></i>
  //<i class='iconfont icon-xiangyou1 rightallow' style='margin-left: 13px;margin-right: 13px'></i>
  let time = `
        <div class='time'>
            <span class='times'>${date.y}年${date.month}月${date.d}日-${newDate.y}年${newDate.month}月${newDate.d}日</span>
        </div>
    `;
  if (number === 1) {
    //time
    div.innerHTML = image + title + time + close;
  } else {
    div.innerHTML = image + title + close;
  }
  return div;
};

let close = () => {
  $(".close").each(function (index) {
    $(this).on("click", function () {
      $(".dialog1")[0] && $(".dialog1")[0].remove();
      $(".dialog2")[0] && $(".dialog2")[0].remove();
      $(".dialog3")[0] && $(".dialog3")[0].remove();
      $(".dialog4")[0] && $(".dialog4")[0].remove();
      $(".dialog5")[0] && $(".dialog5")[0].remove();
      $("#mask")[0].style.display = "none";
    });
  });
};


let createWeek = (teacher) => {
  let frag = document.createDocumentFragment();
  teacher.forEach((item) => {
    let list = createWeekList(item);
    frag.appendChild(list);
  });
  return frag;
};

let createWeekList = (obj) => {
  let list = document.createElement("div");
  list.className = "weeklist";
  list.innerHTML = `
    <div class='week-line'></div>
    <div class='week-name'>${obj.weekday}</div>
    <div class='week-date'>${obj.day}</div>
  `;
  let list2 = document.createElement('div')
  list2.style.cssText = 'height:100%;overflow-y:scroll;overflow-x:hidden'
  obj.time.forEach((item, index) => {
    list2.innerHTML += `
      <div data-week='${obj.weekdaynum}' class='${item === true ? "week-active" : "week-deactive"}'>${activeTime[index]
      }</div>
    `;
  });
  list.appendChild(list2)
  return list;
};

let dialogOneStep = (list) => {
  currentId = list.id
  currentlist = list
  $(".mask")[0].style.display = "block";
  if ($(".block8 ")[0]) {
    $(".block8 ")[0].style.zIndex = 0;
  }
  $(".dialog1")[0] && $(".dialog1")[0].remove();
  let frag = document.createDocumentFragment();
  let wrap = document.createElement("div");
  wrap.className = "dialog1 animated fadeInUp";

  let middle = () => {
    initTeacherTime()
    let week = document.createElement("div");
    week.className = "week";
    timestamp.forEach(item => {
      let day = new Date(item).getDay()
      if (day === 0) day = 6
      else day--
      let hour = new Date(item).getHours()
      if (!isNaN(day) && !isNaN(hour)) {
        teacherTime[day].time[hour] = true
        console.log(day, hour)
      }


      teacherTime[day].time[hour] = true
      console.log(day, hour)
    })
    week.appendChild(createWeek(teacherTime));
    return week;
  };

  let bottom = () => {
    let div = document.createElement("div");
    div.className = "dialog-sure";
    let ldiv = `
            <div class='dialog-sure-wrap'>
                <div style='color:#3C3C3C'>
                    <div>日历位于您的时区${time}</div>
                    <div class='zone-time'>${hour}:${minute}</div>
                </div>
                <div class='sure-time'>确认时间</div>
            </div>
        `;
    div.innerHTML = ldiv;
    return div;
  };


  wrap.appendChild(dialogPublicTop(1));
  wrap.appendChild(middle());
  wrap.appendChild(bottom());
  frag.appendChild(wrap);
  document.body.appendChild(frag);
  setTimer();


  let timeListener = () => {
    $('.week-active').each(function (index) {
      $(this).on('click', (e) => {
        $('.week-active').each(function (index) {
          $('.week-active')[index].className = 'week-active'
        })
        e.target.className = 'week-active week-click'
        clickTime = e.target.innerHTML
        clickDay = e.target.dataset.week

      })
    })
  }
  close();
  timeListener()
};

let dialogTwoStep = () => {
  $(".mask")[0].style.display = "block";
  if ($(".block8 ")[0]) {
    $(".block8 ")[0].style.zIndex = 0;
  }
  let frag = document.createDocumentFragment();
  let wrap = document.createElement("div");
  wrap.className = "dialog2";

  let middle = () => {
    let div = document.createElement("div");
    let top = `
            <div class='now'>现在的水平</div>
        `;
    let bottom = `
            <div class='triangle'>
                <div class='triangle-list'>
                    <div style='height:25px;top: 10px;position: relative;'>上级</div>
                    <div style='height:25px;top: 10px;position: relative;'>more then 5000 words</div>
                    <div style='height:25px;top: 10px;position: relative;'>Advanced</div>
                </div>
                <div class='triangle-list'>
                    <div style='height:25px;top: 10px;position: relative;'>中级</div>
                    <div style='height:25px;top: 10px;position: relative;'>more then 3000 words</div>
                    <div style='height:25px;top: 10px;position: relative;'>Intermediate</div>
                </div>
                <div class='triangle-list'>
                    <div style='height:25px;top: 10px;position: relative;'>初级</div>
                    <div style='height:25px;top: 10px;position: relative;'>more then 1000 words</div>
                    <div style='height:25px;top: 10px;position: relative;'>Elementary</div>
                </div>
                <div class='triangle-list'>
                    <div style='height:25px;top: 10px;position: relative;'>入门</div>
                    <div style='height:25px;top: 10px;position: relative;'>start from Pinyin and tones</div>
                    <div style='height:25px;top: 10px;position: relative;'>Biginner</div>
                </div>
            </div>
        `;
    div.innerHTML = top + bottom;
    return div;
  };

  wrap.appendChild(dialogPublicTop(2));
  wrap.appendChild(middle());
  frag.appendChild(wrap);
  document.body.appendChild(frag);
  triangle();
  close();
};

let dialogThreeStep = (price, data) => {
  let skill = data[0]?.skillname
  $(".mask")[0].style.display = "block";
  if ($(".block8 ")[0]) {
    $(".block8 ")[0].style.zIndex = 0;
  }
  let frag = document.createDocumentFragment();
  let wrap = document.createElement("div");
  wrap.className = "dialog3";

  let middle = () => {
    let wrap = document.createElement("div");
    wrap.className = "dialog3-middle";
    let div = `
            <div class='dialog3-middle-list'>
                <i class='iconfont icon-tiyan' style='font-size:18px'></i>
                <span>信赖我们，直接上课</span>
            </div>
            <div class='dialog3-middle-list2'>
                <i class='iconfont icon-xuexishuben' style='font-size:18px'></i>
                <span>体验课</span>
            </div>
        `;
    wrap.innerHTML = div;
    return wrap;
  };

  let bottom = () => {
    let wrap = document.createElement("div");
    wrap.className = "dialog3-bottom";
    for (let i = 0; i < data?.length; i++) {
      let div = document.createElement('div')
      div.className = 'dialog3-bottom-list'
      div.innerHTML = `
        <i style='font-size: 24px;color:#5686E9' class='iconfont icon-changjinglinghuo'></i>
        <div data-index=${i} style='margin-left: 5%;text-align: center;width: 100px;cursor:pointer' class='dialog3-bottom-list-skill  ${i === 0 ? 'dialog3-bottom-list-active' : 'dialog3-bottom-list-deactive'}'>${data[i].skillname}</div>
        <div style='flex: 1;text-align: right;margin-right: 5%;'>USD</div>
        <div style='width: 20%;'>${currentlist.price ? currentlist.price : price}</div>
      `;
      wrap.appendChild(div)
    }
    return wrap;
  };

  let allPay = () => {
    $('.dialog3-middle-list')[0].addEventListener('click', (e) => {
      let item = {
        userid: currentId,
        coursetime: parseInt(clickDay),
        timequantum: clickTime + ':00',
        tyk: true
      }
      window.location.href = `/views/pay/experience.html?userid=${item.userid}&coursetime=${item.coursetime}&timequantum=${item.timequantum}&tyk=${item.tyk}&skill=${encodeURI(skill)}`
    })
  }

  let experiencePay = () => {
    $('.dialog3-middle-list2')[0].addEventListener('click', (e) => {
      let item = {
        userid: currentId,
        coursetime: parseInt(clickDay),
        timequantum: clickTime + ':00',
        tyk: false
      }
      window.location.href = `/views/pay/experience.html?userid=${item.userid}&coursetime=${item.coursetime}&timequantum=${item.timequantum}&tyk=${item.tyk}&skill=${encodeURI(skill)}`
    })
  }

  let skillListener = () => {
    $('.dialog3-bottom-list-skill').each(function () {
      $(this).on('click', (e) => {
        let { index } = e.target.dataset
        Array.from($('.dialog3-bottom-list-skill')).forEach(item => {
          if (item.dataset.index === index) {
            item.className = 'dialog3-bottom-list-skill dialog3-bottom-list-active'
          } else {
            item.className = 'dialog3-bottom-list-skill dialog3-bottom-list-deactive'
          }
        })
        skill = e.target.innerHTML
      })
    })
  }

  wrap.appendChild(dialogPublicTop(3));
  wrap.appendChild(middle());
  wrap.appendChild(bottom());
  frag.appendChild(wrap);
  document.body.appendChild(frag);
  skillListener();
  close();
  allPay()
  experiencePay()
};

let dialogFiveStep = () => {
  $(".mask")[0].style.display = "block";
  if ($(".block8 ")[0]) {
    $(".block8 ")[0].style.zIndex = 0;
  }
  let frag = document.createDocumentFragment();
  let wrap = document.createElement("div");
  wrap.className = "dialog5";

  let top = () => {
    let div = document.createElement('div')
    div.className = 'dialog5-top'
    div.innerHTML = `
      <div>选择课时,50分钟1节课</div>
      <div>大多数人需要学习40节课以上</div> 
      <div>才能感受到成果,买的越多越优惠.</div>
    `
    return div
  }

  let middle = () => {
    let div = document.createElement('div')
    div.className = 'dialog5-middle'
    div.innerHTML = `
      <div>
        <i class='iconfont icon-huojian' style='color:#3F57AE'></i>
      </div>
      <div>
        <i class='iconfont icon-a-gaotiedongche' style='color:#6A9AC3;font-size:60px'></i>
      </div>
      <div>
        <i class='iconfont icon-qiche_huaban' style='color:#97D8C4'></i>
      </div>
      <div>
        <i class='iconfont icon-zihangche' style='color:#97A6D8'></i>
      </div>
    `
    return div
  }

  let bottom = () => {
    let div = document.createElement('div')
    div.className = 'dialog5-bottom'
    div.innerHTML = `
      <div class='dialog5-bottom-list'>
        <div>120lessons</div>
        <div>9%</div>
        <div>优惠</div>
        <div>有效期32个月</div>
        <div style='color:#81D058'>You save xxx</div>
        <div class='choose'>choose</div>
      </div>
      <div class='dialog5-bottom-list'>
        <div>60lessons</div>
        <div>9%</div>
        <div>优惠</div>
        <div>有效期16个月</div>
        <div style='color:#81D058'>You save xxx</div>
        <div class='choose'>choose</div>
      </div>
      <div class='dialog5-bottom-list'>
        <div>30lessons</div>
        <div>9%</div>
        <div>优惠</div>
        <div>有效期8个月</div>
        <div style='color:#81D058'>You save xxx</div>
        <div class='choose'>choose</div>
      </div>
      <div class='dialog5-bottom-list'>
        <div>15lessons</div>
        <div style='opacity: 0;'>9%</div>
        <div style='opacity: 0;'>优惠</div>
        <div>有效期4个月</div>
        <div style='color:#81D058;opacity: 0;'>You save xxx</div>
        <div class='choose'>choose</div>
      </div>
    `
    return div
  }

  let notion = () => {
    let div = document.createElement('div')
    div.className = 'dialog5-notion'
    div.innerHTML = `
      <svg style="width: 60px;height:70px;margin-left:46px;margin-top:16px" aria-hidden="true">
          <use xlink:href="#icon-dunpai1"></use>
      </svg>
      <div style='margin-left:22px;font-size:10px'>
        <div>100% Satisfaction Guarantee</div>
        <div>The number of prepaid lessons will be displayed under the account balance.</div>
        <div>We release your money to the tutor automatically after the lesson is completed </div>
        <div>unless you report an issue.</div>
        <div>If the lesson didn’t take place, we will issue a refund for that lesson.</div>
      </div>
    `
    return div
  }

  wrap.appendChild(dialogPublicTop(4));
  wrap.appendChild(top())
  wrap.appendChild(middle())
  wrap.appendChild(bottom())
  wrap.appendChild(notion())
  frag.appendChild(wrap)
  document.body.appendChild(frag);

  close();
}

let dialogMessage = (information) => {
  $(".mask")[0].style.display = "block";
  $(".block8 ")[0].style.zIndex = 0;
  let frag = document.createDocumentFragment();
  let wrap = document.createElement("div");
  wrap.className = "dialog4";

  let left = () => {
    let wrap = document.createElement("div");
    wrap.className = "dialog4-left";
    wrap.innerHTML = `
      <svg class='top-icon' style="width: 86px;height:86px;" aria-hidden="true">
         <use xlink:href="#icon-duihua"></use>
      </svg>
      <div class='top-text1'>How does ChineseLessonsOnline work?</div>
      <div class='top-bottom'>
        <i class='iconfont icon-a-xuexiwangke' style='color:#4A9FE1'></i>
        <div class='top-bottom-wrap'>
          <div class='bottom-top'>Meet online</div>
          <div class='bottom-bottom'>Your lesson will happen in our virtual classroom</div>
        </div>
      </div>
      <div class='top-bottom'>
        <i class='iconfont icon-yuedu' style='color:#4A9FE1'></i>
        <div class='top-bottom-wrap'>
          <div class='bottom-top'>Connect easily</div>
          <div class='bottom-bottom'>No installations — join the classroom from your browser</div>
        </div>
      </div>
      <div class='top-bottom'>
        <i class='iconfont icon-anxincai' style='color:#4A9FE1'></i>
        <div class='top-bottom-wrap'>
          <div class='bottom-top'>Stay satisfied</div>
          <div class='bottom-bottom'>Get a free tutor replacement or a refund by request</div>
        </div>
      </div>
    `;
    return wrap;
  };

  let right = () => {
    let wrap = document.createElement("div");
    wrap.className = "dialog4-right";
    wrap.innerHTML = `
      <img width='86' class='source' height='86' src='/static/anquan.png'/>
      <i class='iconfont icon-chahao close'></i>
      <div class='right-text1'>${information.name}老师</div>
      <div class='right-text2'>介绍一下自己，学习目标，提出问题</div>
      <select class='right-select'>
        <option value="" disabled selected>为什么学习中文</option>
        <option>工作</option>
        <option>教育</option>
        <option>旅行</option>
        <option>爱好</option>
        <option>亲朋好友</option>
      </select>
      <div contenteditable class='right-attend' placeholder='希望达到的目标'></div>
      <div class='right-bottom'>
        <div class='right-bottom-text'>${information.name}老师，你好</div>
        <div class='right-bottom-content' contenteditable placeholder='留言'></div>
      </div>
      <label class='right-check'>
        <input type='checkbox' class='right-check-input' />
        <span>分享给其他老师，获得更多回答。</span>

      </label>
      <div class='right-send'>发送</div>
      `;
    /**
     * <div class='check-right'>
        <img width='24' height='23' src='../../static/anquan.png'/>
        <img class='check-right-z' width='24' height='23' src='../../static/anquan.png'/>
        <img class='check-right-z' width='24' height='23' src='../../static/anquan.png'/>
      </div>
     */
    return wrap;
  };

  wrap.appendChild(left());
  wrap.appendChild(right());
  frag.appendChild(wrap);
  document.body.appendChild(frag);
  close();
};

let setTimer = () => {
  let time = $(".zone-time")[0];
  setInterval(() => {
    time.innerHTML = `
            ${new Date().getHours() > 10
        ? new Date().getHours()
        : "0" + new Date().getHours()
      } : ${new Date().getMinutes() > 10
        ? new Date().getMinutes()
        : "0" + new Date().getMinutes()
      }
        `;
  }, 1000);
};

let createTeacherList = () => {
  $(".block18")[0].innerHTML = ''
  let wrap = document.createDocumentFragment();
  list.forEach((item, index) => {
    let strNum = getBLen(item.selfintroduction);
    let l = document.createElement("div");
    l.dataset.index = index + 1 + "";
    l.dataset.teacherid = item.id;
    l.className = `block19 ${index === 0 ? "" : "block55"} animated fadeInDown`;
    l.innerHTML = `
            <div class='block21'>
                <div class="block22">
                    <img src="${item.teacherimg
      }" width="120" height="165" alt="" style='object-fit: cover;'>
                </div>
                <div class="block23">
                    <div class="block24">
                        <div style="font-size: 20px;">${item.name}</div>
                        <svg style="width: 22px;height:14px;margin-left:13px" aria-hidden="true">
                            <use xlink:href="#icon-zhongguo"></use>
                        </svg>
                        <svg style="width: 17px;height:19px;margin-left:13px" aria-hidden="true">
                            <use xlink:href="#icon-mianxingchanpinbaohubaoxianrenzhengdunpaibaozheng"></use>
                        </svg>
                    </div>
                    <div class="block25">${item.teachercurriculumsection}节课</div>
                    <div class="block26">
                        <div>母语</div>
                        <div class="block27">${item.language}</div>
                        <div class="block29">${item.language}</div>
                        <div class="block27 block28">${item.degree}</div>
                    </div>
                    <div class="block30" style='${strNum >= 90 ? "" : "overflow:hidden"
      }'>
                        ${item.selfintroduction}
                    </div>
                </div>
                <div class="block33">
                    <div class="block34">
                        <div>
                            <i class="iconfont icon-B-pingfen" style="color: #FDC425;"></i>
                            <span class="block36">${item.star}</span>
                        </div>
                        <div class="block37">$${item.price}</div>
                    </div>
                    <div class="block38">
                        <div>${item.comment_quantity}条评论</div>
                        <div>一课时</div>
                    </div>
                    <div class="block39">预约体验课</div>
                    <div class="block40">发送消息</div>
                </div>
            </div>
        `;
    wrap.appendChild(l);
  });
  $(".block18")[0].appendChild(wrap);
};

let createTeacherList2 = () => {
  $('.list2')[0].innerHTML = ''
  let wrap = document.createDocumentFragment()
  list2.forEach((item, index) => {
    let strNum = getBLen(item.selfintroduction);
    let l = document.createElement("div");
    l.dataset.index = index + 4 + "";
    l.dataset.teacherid = item.id;
    l.className = `block19 ${index === 0 ? "" : "block77"} wow slideInDown animated`;
    l.innerHTML = `
            <div class='block21'>
                <div class="block22">
                    <img src="${item.teacherimg
      }" width="120" height="165" alt="">
                </div>
                <div class="block23">
                    <div class="block24">
                        <div style="font-size: 20px;">${item.name}</div>
                        <svg style="width: 22px;height:14px;margin-left:13px" aria-hidden="true">
                            <use xlink:href="#icon-zhongguo"></use>
                        </svg>
                        <svg style="width: 17px;height:19px;margin-left:13px" aria-hidden="true">
                            <use xlink:href="#icon-mianxingchanpinbaohubaoxianrenzhengdunpaibaozheng"></use>
                        </svg>
                    </div>
                    <div class="block25">${item.teachercurriculumsection}节课</div>
                    <div class="block26">
                        <div>母语</div>
                        <div class="block27">${item.language}</div>
                        <div class="block29">${item.language}</div>
                        <div class="block27 block28">${item.degree}</div>
                    </div>
                    <div class="block30" style='${strNum >= 90 ? "" : "overflow:hidden"
      }'>
                        ${item.selfintroduction}
                    </div>
                </div>
                <div class="block33">
                    <div class="block34">
                        <div>
                            <i class="iconfont icon-B-pingfen" style="color: #FDC425;"></i>
                            <span class="block36">${item.star}</span>
                        </div>
                        <div class="block37">$${item.price}</div>
                    </div>
                    <div class="block38">
                        <div>${item.comment_quantity}条评论</div>
                        <div>一课时</div>
                    </div>
                    <div class="block39">预约体验课</div>
                    <div class="block40">发送消息</div>
                </div>
            </div>
        `;
    wrap.appendChild(l);
  });
  $(".list2")[0].appendChild(wrap);
};

let createPage = () => {
  $('.block78')[0] && $('.block78')[0].remove()
  let block78 = document.createElement("div");
  block78.className = "block78 animated slideInDown";
  let before = document.createElement('div')
  before.className = 'block79 page-before'
  before.innerText = '<'
  allPage = Math.ceil(total / 10)
  block78.appendChild(before)
  for (let i = 0; i < (allPage > 5 ? 5 : allPage); i++) {
    let page = document.createElement('div')
    page.className = `block79 block80 page-click ${i === 0 ? '' : 'page-noselect'}`
    page.innerText = `${i + 1}`
    block78.appendChild(page)
    n[i + 1] = i + 1
  }
  let next = document.createElement('div')
  next.className = 'block79 block80 page-noselect next-page'
  next.innerText = '>'
  block78.appendChild(next)
  $('.block73')[0].appendChild(block78);
}

let nextPageListener = () => {
  $(".next-page")[0].addEventListener("click", async (e) => {
    if (currentPage >= allPage) return false;
    if (index >= 5) index = 1
    else index++
    let parent = $(e.target).parent()[0];
    let frag = document.createDocumentFragment();

    for (let i = 0; i < 7; i++) {
      if (i === 0) {
        let div = document.createElement("div");
        div.className = "block79 page-before";
        div.innerHTML = "<";
        frag.appendChild(div);
      } else if (i === 6) {
        let div = document.createElement("div");
        div.className = "block79 block80 page-noselect next-page";
        div.innerHTML = ">";
        frag.appendChild(div);
      } else {
        let div = document.createElement("div");
        if (i === index) {
          div.className = "block79 block80 page-click";
        } else {
          div.className = "block79 block80 page-noselect page-click";
        }
        if (index === 1) {
          n[i] += 5
          if (n[i] <= total) {
            div.innerHTML = n[i] + ''
            frag.appendChild(div);
          }

        } else {
          if (n[i] && n[i] <= allPage) {
            div.innerHTML = n[i]
            frag.appendChild(div);
          }

        }
      }
    }
    currentPage++;
    parent.innerHTML = "";
    parent.appendChild(frag);
    nextPageListener();
    lastPageListener();
    clickPageListener();
    getParams.pageNum = currentPage
    let res = await ajax("looking_teachers", getParams, "post");
    list = res.data.list.splice(0, 4)
    list2 = res.data.list
    createTeacherList()
    createTeacherList2()
    clearBlock20Style()
    listenerDialogOpen()
  });
};

let lastPageListener = () => {
  $(".page-before")[0].addEventListener("click", async (e) => {
    if (currentPage <= 1) return false;
    if (index <= 5 && index !== 1) index--
    else index = 5
    let parent = $(e.target).parent()[0];
    let frag = document.createDocumentFragment();
    for (let i = 0; i < 7; i++) {
      if (i === 0) {
        let div = document.createElement("div");
        div.className = "block79 page-before";
        div.innerHTML = "<";
        frag.appendChild(div);
      } else if (i === 6) {
        let div = document.createElement("div");
        div.className = "block79 block80 page-noselect next-page";
        div.innerHTML = ">";
        frag.appendChild(div);
      } else {
        let div = document.createElement("div");
        if (i === index) {
          div.className = "block79 block80 page-click";
        } else {
          div.className = "block79 block80 page-noselect page-click";
        }
        if (index === 5) {
          n[i] -= 5
          div.innerHTML = n[i] + ''
          frag.appendChild(div);
        } else {
          if (n[i] && n[i] <= allPage) {
            div.innerHTML = n[i]
            frag.appendChild(div);
          }
        }
      }
    }
    currentPage--;
    parent.innerHTML = "";
    parent.appendChild(frag);
    lastPageListener();
    nextPageListener();
    clickPageListener();
    getParams.pageNum = currentPage
    let res = await ajax("looking_teachers", getParams, "post");
    list = res.data.list.splice(0, 4)
    list2 = res.data.list
    createTeacherList()
    createTeacherList2()
    clearBlock20Style()
    listenerDialogOpen()
  });
};

let clickPageListener = () => {
  $('.page-click').each(function (u) {
    $(this).on('click', async function (e) {
      let text = e.target.innerText
      console.log(currentPage)
      if (parseInt(text) === currentPage) return
      Array.from($(e.target).parent().children()).forEach((item, j) => {
        if (item.innerText === text) {
          item.className = 'block79 block80 page-click'
          currentPage = parseInt(text)
          index = j
        } else if (item.innerText !== '<' && item.innerText !== '>') {
          item.className = 'block79 block80 page-click page-noselect'
        }
      })
      getParams.pageNum = currentPage
      let res = await ajax("looking_teachers", getParams, "post");
      list = res.data.list.splice(0, 4)
      list2 = res.data.list
      createTeacherList()
      createTeacherList2()
      clearBlock20Style()
      listenerDialogOpen()
    })
  })
}

let createOtherBottom = () => {
  let block73 = $(".block73")[0];
  let frag = document.createDocumentFragment();
  let block81 = document.createElement("div");
  block81.className = "block81 wow fadeInDown animated";
  block81.innerHTML = "我们的老师";
  let block82 = document.createElement("div");
  block82.className = "block82 wow fadeInDown animated";
  block82.innerHTML = `
    <div class="block83">
        <div class="block84">
            <i class="iconfont icon-B-pingfen block85"></i>
            <i class="iconfont icon-B-pingfen block85"></i>
            <i class="iconfont icon-B-pingfen block85"></i>
            <i class="iconfont icon-B-pingfen block85"></i>
            <i class="iconfont icon-B-pingfen block85"></i>
        </div>
        <div class="block86">平均评价四颗星以上！</div>
    </div>
    <div class="block83 block87">
        <div class="block84">
            <svg style="width: 55px;height:55px;margin-left:13px" aria-hidden="true">
                <use xlink:href="#icon-diqiu1"></use>
            </svg>
        </div>
        <div class="block86">平均会说三种语言！</div>
    </div>
    <div class="block83 block87">
        <div class="block84">
            <i class="iconfont icon-duihuaxinxitianchong" style="font-size: 55px;"></i>
        </div>
        <div class="block86">平均一小时内给您回复</div>
    </div>
  `;
  let block88 = document.createElement("div");
  block88.className = "block88 wow fadeInDown animated";
  block88.innerHTML = "寻找老师";
  let block89 = document.createElement("div");
  block89.className = "block89 wow fadeInDown animated";
  block89.innerHTML = "做我的老师吧";
  frag.appendChild(block81);
  frag.appendChild(block82);
  frag.appendChild(block88);
  frag.appendChild(block89);
  block73.appendChild(frag);
};

let createBestTeacherList = () => {
  let wrap = document.createDocumentFragment();
  //<i class="iconfont icon-yunhang block74"></i>
  bestTeacher.forEach((item, index) => {
    let i = document.createElement("div");
    i.className = `block59 ${index === 0 ? "" : "block72"}`;
    i.innerHTML = `
        <div class="block60">
            <video controls style='width:100%; height:100%; object-fit: fill'>
              <source src="${item.video}" type="video/mp4">
            </video>
            
        </div>
        <div class="block61">
            <div class="block24 block62 block70">
                <div style="font-size: 20px;">${item.name}</div>
                <svg style="width: 22px;height:14px;margin-left:13px" aria-hidden="true">
                    <use xlink:href="#icon-zhongguo"></use>
                </svg>
                <svg style="width: 17px;height:19px;margin-left:13px" aria-hidden="true">
                    <use xlink:href="#icon-mianxingchanpinbaohubaoxianrenzhengdunpaibaozheng"></use>
                </svg>
            </div>
            <div class="block62 block63">
                <span class="block64">$${item.price}</span>
                <div class="block65">
                    <div class="block67" style="margin-right: 21px;">
                        <i class="iconfont icon-xinxi2 block76"></i>
                        <i class="iconfont icon-B-pingfen block75"></i>
                        <span class="block66">x${item.star}</span>
                    </div>
                    <div class="block67">
                        <i class="iconfont icon-boshimaobeifen block76"></i>
                        <i class="iconfont icon-B-pingfen block75"></i>
                        <span class="block66">x${item.star}</span>
                    </div>
                </div>
            </div>
            <div class="block62 block63 block69">
                <div>母语：${item.language} </div>
                <div class="block68">使用语言：${item.language}</div>
            </div>
            <div class="block62 block63 block71">查看老师完整档案</div>
        </div>
    `;
    wrap.appendChild(i);
  });
  $(".block58")[0].appendChild(wrap);
};

let triangle = () => {
  $(".triangle-list").each(function (index) {
    $(this).on("click", async function () {
      $(".dialog2")[0].remove();
      let { data } = await ajax('looking_teachers_money', {
        'userid': currentId,
        'coursetime': clickDay,
        'timequantum': clickTime + ':00'
      }, 'post')
      let res = await ajax('student_teacher_query_skill', {
        'userid': currentId,
      }, 'post')
      console.log('s', res)
      if (data) {
        dialogThreeStep(data.price, res?.data);
      } else {
        dialogThreeStep()
      }

    });
  });
};

let sureButton = () => {
  $(".sure-time")[0].addEventListener("click", () => {
    if (clickTime) {
      $(".dialog1")[0].remove();
      dialogTwoStep();
    } else {
      Dreamer.warning('请填写预约的时间', 2000);
    }

  });
};

let listenerTop = () => {
  $('.check').each(function (index) {
    $(this).on('click', function (e) {
      if (selectCountry.includes(e.target.value)) {
        let index = selectCountry.indexOf(e.target.value)
        selectCountry.splice(index, 1)
        getParams.birthplace = selectCountry.length === 0 ? '' : selectCountry.join(',')
      } else {
        selectCountry.push(e.target.value)
        getParams.birthplace = selectCountry.join(',')
      }
      if (selectCountry.length === 0) {
        $('.selectArea')[0].innerText = '选择出生地'
      } else {
        $('.selectArea')[0].innerText = selectCountry.join(',')
        getParams.birthplace = selectCountry.join(',')
      }
      initSelectPage()
    })
  })

  $('.checkskill').each(function (index) {
    $(this).on('click', function (e) {
      if (selectSkill.includes(e.target.value)) {
        let index = selectSkill.indexOf(e.target.value)
        selectSkill.splice(index, 1)
        getParams.dialect = selectSkill.length === 0 ? '' : selectSkill.join(',')
      } else {
        selectSkill.push(e.target.value)
        getParams.dialect = selectSkill.join(',')
      }
      if (selectSkill.length === 0) {
        $('.selectGood')[0].innerText = '选择擅长'
      } else {
        $('.selectGood')[0].innerText = selectSkill.join(',')
        getParams.dialect = selectSkill.join(',')
      }
      initSelectPage()
    })
  })

  $('.checklanguage').each(function (index) {
    $(this).on('click', function (e) {
      if (selectLanguge.includes(e.target.value)) {
        let index = selectLanguge.indexOf(e.target.value)
        selectLanguge.splice(index, 1)
        getParams.language = selectSkill.length === 0 ? '' : selectSkill.join(',')
      } else {
        selectLanguge.push(e.target.value)
        getParams.language = selectLanguge.join(',')
      }
      if (selectLanguge.length === 0) {
        $('.selectLanguage')[0].innerText = '选择语言'
      } else {
        $('.selectLanguage')[0].innerText = selectLanguge.join(',')
        getParams.language = selectLanguge.join(',')
      }
      initSelectPage()
    })
  })

  $('.block100')[0].oninput = () => {
    Array.from($('.block104')[0].children).forEach(item => {
      if (!$('.block100')[0].value) {
        $(item).show()
        $(item.children[0]).on('click', (e) => {
          $('.selectArea')[0].innerText = selectCountry.join(',')
          getParams.birthplace = selectCountry.join(',')
        })
      }
      else if (item.children[1].innerText != $('.block100')[0].value) {
        $(item).hide()
      } else {
        $(item).show()
        $(item.children[0]).on('click', (e) => {
          $('.selectArea')[0].innerText = selectCountry.join(',')
          getParams.birthplace = selectCountry.join(',')
        })
      }
      // initSelectPage(getParams)
    })

  }

  $('.block112').each(function (index) {
    $(this).on('click', function () {

      selectTime = $(this).children('span')[0].innerHTML
      $('.selectTime')[0].innerHTML = selectDay + '  ' + selectTime + '点'
      let time1 = selectTime.split('~')[0]
      let time2 = selectTime.split('~')[1]
      if (time1 < 10) {
        time1 = '0' + time1
        time1 += ':00:00'
      } else {
        time1 += ':00:00'
      }
      if (time2 < 10) {
        time2 = '0' + time2
        time2 += ':00:00'
      } else {
        time2 += ':00:00'
      }
      getParams.timequantum = time1
      getParams.timequantum1 = time2
      if (selectDay) {
        let week = {
          '星期一': 1,
          '星期二': 2,
          '星期三': 3,
          '星期四': 4,
          '星期五': 5,
          '星期六': 6,
          '星期日': 7,
        }
        getParams.coursetime = week[selectDay]
        initSelectPage('query_teacher_time_one')
      }
    })
  })

  $('.block119').each(function (index) {
    $(this).on('click', function () {
      selectDay = this.innerText
      if (selectTime) {
        $('.selectTime')[0].innerHTML = selectDay + '   ' + selectTime + '点'
        let time1 = selectTime.split('~')[0]
        let time2 = selectTime.split('~')[1]
        if (time1 < 10) {
          time1 = '0' + time1
          time1 += ':00:00'
        } else {
          time1 += ':00:00'
        }
        if (time2 < 10) {
          time2 = '0' + time2
          time2 += ':00:00'
        } else {
          time2 += ':00:00'
        }
        getParams.timequantum = time1
        getParams.timequantum1 = time2
        let week = {
          '星期一': 1,
          '星期二': 2,
          '星期三': 3,
          '星期四': 4,
          '星期五': 5,
          '星期六': 6,
          '星期日': 7,
        }
        getParams.coursetime = week[selectDay]
        initSelectPage('query_teacher_time_one')
      } else {
        $('.selectTime')[0].innerHTML = selectDay
        getParams.teachingt = selectDay
      }
    })
  })

  $('.filter-select')[0].onclick = () => {
    $('.filter').slideToggle()
  }

  $('.filter-div').each(function (index) {
    $(this).on('click', (e) => {
      $('.block13')[0].children[0].innerText = e.target.innerText
      $('.filter').slideToggle()
      let key = e.target.dataset.key.split('-')[0]
      let value = e.target.dataset.key.split('-')[1]
      let obj = {
        price: '',
        star: ''
      }
      obj[key] = value
      Object.assign(getParams, obj)
      initSelectPage()
    })
  })

  $('.header-input')[0].addEventListener('change', (e) => {
    getParams.name = e.target.value

  })

  $('.header-icon-search')[0].addEventListener('click', () => {
    initSelectPage()
  })
}

let priceChangeListener = () => {
  let bar = $('.block96')[0],
    scroll = $('.block95')[0],
    mask = $('.block97')[0],
    leftVal = 0
  window.requestAnimationFrame(() => {
    bar.onmousedown = async function (event) {
      var event = event || window.event;
      var leftVal = event.clientX - this.offsetLeft;
      var that = this;
      // 拖动一定写到 down 里面才可以
      document.onmousemove = function (event) {
        var event = event || window.event;
        var barleft = event.clientX - leftVal;
        if (barleft < 0)
          barleft = 0;
        else if (barleft > scroll.offsetWidth - bar.offsetWidth)
          barleft = scroll.offsetWidth - bar.offsetWidth;
        if (barleft >= $('.block95')[0].offsetWidth) {
          mask.style.width = 304 + 'px';
          that.style.left = 282 + "px";
        } else {
          mask.style.width = barleft + 'px';
          that.style.left = barleft + "px";
        }
        let width = parseInt(barleft / (scroll.offsetWidth - bar.offsetWidth) * 10000)
        if (width < $('.block99')[0].value) {
          width = parseInt($('.block99')[0].value) + 1
        }

        $('.block99')[1].value = `${width}`
        $('.money')[0].innerText = `$${$('.block99')[0].value}-$${width}`
        //防止选择内容--当拖动鼠标过快时候，弹起鼠标，bar也会移动，修复bug
        window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
      }
      getParams.price = $('.block99')[0].value
      getParams.price1 = $('.block99')[1].value
      console.log(getParams)
      // let data = {
      //   price: parseInt($('.block99')[0].value),
      //   price1: parseInt($('.block99')[1].value)
      // }
      // Object.assign(getParams, data)
      // initSelectPage()
    }

    document.onmouseup = function (e) {
      if (e.target.className.includes('block96')) {
        document.onmousemove = null; //弹起鼠标不做任何操作
        let data = {
          price: parseInt($('.block99')[0].value),
          price1: parseInt($('.block99')[1].value)
        }
        Object.assign(getParams, data)
        initSelectPage()
      }

    }
  })

}

let mins = () => {
  $('.block99')[0].addEventListener('input', async (e) => {
    if ($('.block99')[0].value >= 10000) {
      $('.block99')[0].value = $('.block99')[0].value.substring(0, 2)
    } else if (!$('.block99')[0].value) {
      $('.block99')[0].value = 1
    } else {
      $('.block99')[0].value = parseInt($('.block99')[0].value)
    }
    $('.money')[0].innerText = `$${$('.block99')[0].value}-$${$('.block99')[1].value}`
    let data = {
      price: parseInt($('.block99')[0].value),
      price1: parseInt($('.block99')[1].value)
    }
    Object.assign(getParams, data)
    initSelectPage()
  })
}

let initSelectPage = async (url = 'query_teacher_puls') => {
  loading.showLoading({
    type: 1,
    tip: "loading..."
  })
  let res = await ajax(url, getParams, "post");
  if (res?.data?.list?.length) {
    loading.hideLoading()
    total = res.data.total
    list = res.data.list.splice(0, 4)
    list2 = res.data.list
    createTeacherList()
    createTeacherList2()
    clearBlock20Style()
    listenerDialogOpen()
    createPage()
    lastPageListener();
    nextPageListener();
    clickPageListener();
    $('.block57')[0].style.marginTop = '40px'
    $('.block20')[0].style.opacity = '1'
  } else {
    loading.hideLoading()
    Dreamer.error('no looking...')
    total = 1
    list = []
    list2 = []
    createTeacherList()
    createTeacherList2()
    listenerDialogOpen()
    $('.block20')[0].style.opacity = '0'
    $('.block57')[0].style.marginTop = '0px'
    $('.block78')[0] && $('.block78')[0].remove()
  }

}

let maxs = () => {
  $('.block99')[1].addEventListener('input', async (e) => {
    if ($('.block99')[1].value > 10000) {
      $('.block99')[1].value = $('.block99')[1].value.substring(0, 2)
    } else if (!$('.block99')[1].value) {
      $('.block99')[1].value = 2
    } else {
      $('.block99')[1].value = parseInt($('.block99')[1].value)
    }
    $('.money')[0].innerText = `$${$('.block99')[0].value}-$${$('.block99')[1].value}`
    let data = {
      price: parseInt($('.block99')[0].value),
      price1: parseInt($('.block99')[1].value)
    }
    Object.assign(getParams, data)
    initSelectPage()
  })

}


let getBLen = function (str) {
  if (str == null) return 0;
  if (typeof str != "string") {
    str += "";
  }
  return str.replace(/[^\x00-\xff]/g, "01").length;
};

// listen agora channel or user one point one message
let listenerAgora = async () => {
  let { client, channel } = await loginRTM()

  client.on('MessageFromPeer', function (message, peerId, r) {

  })
  clients = client

}


export {
  dialogOneStep,
  dialogFiveStep,
  sureButton,
  createTeacherList,
  createTeacherList2,
  clickPageListener,
  createBestTeacherList,
  createOtherBottom,
  getTeacher,
  nextPageListener,
  lastPageListener,
  maxs,
  mins
};
